package com.zhiwang.planet.ui.my

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.PhoneBindEvent
import com.zhiwang.planet.mvp.p.GraphCodePresenter
import com.zhiwang.planet.mvp.p.SmsCodePresenter
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.v.BindWxView
import com.zhiwang.planet.mvp.v.GraphView
import com.zhiwang.planet.mvp.v.SmsCodeView
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.util.AppHelper
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.suicideAfterTransition
import kotlinx.android.synthetic.main.activity_wx_bind.*
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

class BindPhoneActivity : BaseActivity(), SmsCodeView, BindWxView, GraphView {

    @Inject
    lateinit var userPresenter: UserPresenter

    @Inject
    lateinit var smsCodePresenter: SmsCodePresenter

    @Inject
    lateinit var graphCodePresenter: GraphCodePresenter

    @Deprecated("已经废弃，目前使用新逻辑，由于绑定手机号被延后到在 “我的”页面点击提现才会绑定手机号，所以不再需要openid")
    private val oldUserClickSpan = object : ClickableSpan() {
        override fun onClick(widget: View) {
            WxOldUserBindActivity.start(this@BindPhoneActivity, openid ?: "")
        }
    }

    var token: String = System.currentTimeMillis().toString()

    var openid: String? = ""

    companion object SOUL {
        fun start(context: Context, code: String) {
            val intent = Intent(context, BindPhoneActivity::class.java)
            intent.putExtra("Openid", code)
            context.startActivity(intent)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wx_bind)
        setSupportActionBar(toolbar)
        openid = intent.getStringExtra("Openid")
        init()
    }

    override fun initInjection() {
        DaggerUserComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(this))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        userPresenter.bindWxView = this
        graphCodePresenter.graphView = this
    }

    private fun init() {

        val s = old_user_bind_link.text.toString()
        val spannableString = SpannableString(s)
        spannableString.setSpan(oldUserClickSpan, 0, s.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        old_user_bind_link.text = spannableString
        observeTextChangeWithTargetButtonEnableStatus(arrayOf(et_phone, smsCodeEditor, graphCodeEditor), confirm_button)
        getGraphCode(graphCodeBtn)
    }

    fun getGraphCode(view: View) {
        token = System.currentTimeMillis().toString()
        Glide.with(view)
                .load((if (BuildConfig.DEBUG && AppHelper.testEnv()) BuildConfig.DEBUG_TEST_BASE_URL else BuildConfig.BASE_URL) + "api/app_vcode?tu_token=$token&vcode_type=app_bindphone")
                .into(view as ImageView)
//        graphCodePresenter.getRegisterGraphCode(token)
    }

    fun getSmsCode(view: View) {
        val phone = et_phone.text.toString()
        val graphCode = graphCodeEditor.text.toString()

        smsCodePresenter.getPhoneBindSmsCode(phone, token, graphCode, ::onSmsSend, ::onSmsError)
    }

    override fun onGraphCodeLoad(b: Bitmap) {
        graphCodeBtn.setImageBitmap(b)
    }

    fun onSmsError(msg: String) {
        Toaster.message(msg)
        getGraphCode(graphCodeBtn)
    }


    override fun onSmsSend() {
        captchaTextView.start()
        Toaster.message("短信验证码已发送")
    }

    fun bind(v: View) {
        val phone = et_phone.text.toString()
        val sms = smsCodeEditor.text.toString()
        userPresenter.bindPhone(phone, sms /*openid ?: ""*/)
    }

    override fun onWxBind() {
        Toaster.message("手机号绑定成功")
        EventBus.getDefault().post(PhoneBindEvent)
        suicideAfterTransition()
    }

    override fun onError(t: Throwable) {
        getGraphCode(graphCodeBtn)
        super.onError(t)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }
}
